﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Qu.SeniorProject.Model;
using Qu.SeniorProject.WebUI.Utils;
using System.Web;
using System.IO;

namespace Qu.SeniorProject.WebUI.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult Upload (HttpPostedFileBase file) //(string qqfile)
        {
            var docType = Request["DocumentType"];
            int projectId = int.Parse(Request["ProjectId"]);
            string docExtension = Request["DocumentExtension"];
            string academicYear = Request["AcademicYear"];

            var destinationFolder = Path.Combine(this.Server.MapPath("~/uploads/"), academicYear); //DateTime.Now.Year.ToString());

            if (!System.IO.Directory.Exists(destinationFolder))
                System.IO.Directory.CreateDirectory(destinationFolder);

            destinationFolder = Path.Combine(destinationFolder, docType);

            if (!System.IO.Directory.Exists(destinationFolder))
                System.IO.Directory.CreateDirectory(destinationFolder);

            var fileName = string.Format("Project{0}-{1}{2}", projectId, docType, docExtension);
            var filePath = Path.Combine(destinationFolder, fileName);

            var docUrl = HttpUtility.HtmlEncode(string.Format("{0}{1}/{2}/{3}", "uploads/", academicYear, docType, fileName));

            try
            {
                //HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
                file.SaveAs(filePath);

                //var stream = Request.InputStream;
                ////if (String.IsNullOrEmpty(Request["qqfile"]))
                ////{
                ////    // IE
                ////    HttpPostedFileBase postedFile = Request.Files[0];
                ////    stream = postedFile.InputStream;
                ////    file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
                ////}
                ////else
                ////{
                ////    //Webkit, Mozilla
                ////    file = Path.Combine(path, qqfile);
                ////}

                //var buffer = new byte[stream.Length];
                //stream.Read(buffer, 0, buffer.Length);
                //System.IO.File.WriteAllBytes(filePath, buffer);
                //stream.Flush();
                //stream.Close();

                var userInfo = Session["UserInfo"] as UserInfo;
                var projectDocument = new ProjectDocument
                {
                    ProjectId = projectId,
                    DocumentType = docType,
                    DocumentExtension = docExtension,
                    DocumentPath = docUrl,
                    DocumentName = fileName,
                    SubmittedBy = userInfo.LoginName
                };

                ProjectRepository.AddProjectDocument(projectDocument);
                TempData["Message"] = string.Format("File '{0}' uploaded successfully", file.FileName);
            }
            catch (Exception ex)
            {
                TempData["Message"] = string.Format("File '{0}' upload failed {1}", file.FileName, ex.Message);
                 return RedirectToAction("Index");
            }
            return RedirectToAction("Index");

            //catch (Exception ex)
            //{
            //    return Json(new { success = false, message = ex.Message }, "text/html");
            //}

            //return Json(new { success = true, message = string.Format("<a href='{0}'>{1}</a>", docUrl, fileName) }, "text/html");

            //var destinationFolder = string.Format("{0}{1}", this.Server.MapPath("~/uploads/"), DateTime.Now.Year);

            //if (!System.IO.Directory.Exists(destinationFolder))
            //    System.IO.Directory.CreateDirectory(destinationFolder);

            //var fileName = string.Format("Project{0}-{1}{2}", Request["ProjectId"], Request["DocumentType"], Request["DocumentExtension"]);
            //var filePath = string.Format(@"{0}\{1}", destinationFolder, fileName);
            //fileData.SaveAs(filePath);

            //var url = HttpUtility.HtmlEncode(string.Format("{0}{1}/{2}", "uploads/", DateTime.Now.Year, fileName));
            //return string.Format("<a href='{0}'>{1}<a>", url, fileName);

        }

        public ActionResult AvailableProjects()
        {
            ViewBag.Message = "Available Projects";
            var projects = ProjectRepository.GetProjectsSummary("ProjectsWithoutStudent");
            return View("Projects", projects);
        }

        public ActionResult AvailableStudents()
        {
            UserInfo userInfo = Session["UserInfo"] as UserInfo;

            if (userInfo != null && userInfo.IsFaculty)
                ViewBag.CanAddProject = ProjectRepository.CanAddProject(int.Parse(userInfo.UserID));

            ViewBag.Message = "Students looking for Supervisor";
            var projects = ProjectRepository.GetProjectsSummary("ProjectsWithoutSupervisor");
            return View("Projects", projects);
        }

        public ActionResult AvailableSupervisors()
        {
            var supervisors = ProjectRepository.GetAvailableSupervisors();
            return View(supervisors);
        }

        [Authorize]
        [HttpGet]
        public ActionResult AddProject()
        {
            PopulateDropDowns();

            Project proj = new Project();

            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo != null && userInfo.IsStudent)
            {
                proj.StudentIDs = new List<string> { userInfo.UserID };
                ViewBag.IsStudent = true;
            }

            if (userInfo != null && userInfo.IsFaculty)
                proj.SupervisorID = int.Parse(userInfo.UserID);

            ViewBag.Title = "Add Project";

            return View(proj);
        }

        [HttpPost]
        public ActionResult AddProject(Project project, string[] students)
        {
            PopulateDropDowns();

            ViewBag.Title = "Add Project";

            if (students != null)
                project.StudentIDs = new List<string>(students.ToList());

            string validationError = ControllerHelper.ValidateStudents(project.StudentIDs);
            if (!string.IsNullOrEmpty(validationError))
            {
                ModelState.AddModelError("StudentIDs", validationError);
                return View(project);
            }

            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo != null)
            {
                project.UpdatedBy = userInfo.LoginName;
                project.UpdatedDate = DateTime.Now;
            }
            int projectID = ProjectRepository.AddProject(project);

            TempData["PeriodID"] = project.PeriodId;
            TempData["Message"] = "Project Added successfully.";
            return RedirectToAction("Index");
            //ViewBag.Message = "Project Added successfully.";
            //return View();
        }


        [Authorize]
        [HttpGet]
        public ActionResult EditProject(int projectId, string title="Edit Project", bool setSupervisor = false)
        {
            PopulateDropDowns();

            Project proj = ProjectRepository.GetProject(projectId);

            ViewBag.Title = title;

            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo != null && userInfo.IsStudent)
                ViewBag.IsStudent = true;

            else if (userInfo.IsFaculty && setSupervisor )
                proj.SupervisorID = int.Parse(userInfo.UserID);
            
            return View("AddProject", proj);
        }

        [HttpPost]
        [Authorize]
        public ActionResult EditProject(Project project, string[] students)
        {
            PopulateDropDowns();

            ViewBag.Title = "Edit Project";

            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo != null && userInfo.IsStudent)
            {
                ViewBag.IsStudent = true;
            }

            if (students != null)
                 project.StudentIDs = new List<string>(students.ToList());

            string validationError = ControllerHelper.ValidateStudents(project.StudentIDs);
            if (!string.IsNullOrEmpty(validationError))
            {
                ModelState.AddModelError("StudentIDs", validationError);
                return View("AddProject", project);
            }

            if (userInfo != null)
            {
                project.UpdatedBy = userInfo.LoginName;
                project.UpdatedDate = DateTime.Now;
            }

            ProjectRepository.UpdateProject(project);

            //ViewBag.Message = "Project Updated successfully.";
            //return View("AddProject", project);
            //ToDo: pass this to the Index and display it
            TempData["PeriodID"] = project.PeriodId;
            TempData["Message"] = "Project Updated successfully.";
            return RedirectToAction("Index");
        }

        [HttpGet]
        [Authorize]
        public ActionResult ProjectDetails(int id)
        {
            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (userInfo != null && userInfo.IsAdmin)
                ViewBag.IsAdmin = true;

            int facultyID = (userInfo.IsFaculty ? int.Parse(userInfo.UserID) : 0);

            ProjectSummary proj = ProjectRepository.GetProjectSummary(id, facultyID);

            return View(proj);
        }

        //[HttpGet]
        //public PartialViewResult StudentInfo()
        //{
        //    return PartialView();
        //}

        //[HttpPost]
        //public ActionResult GetStudents(string query)
        //{
        //    return Json(UserRepository.GetStudents(query));
        //}

        //[Authorize]
        //[HttpGet]
        //public ActionResult ReviewProject()
        //{
        //    UserInfo userInfo = Session["UserInfo"] as UserInfo;
        //    if (Request.IsAuthenticated && userInfo == null)
        //    {
        //        //Store the User Info in a Session
        //        userInfo = UserRepository.GetUserInfo(User.Identity.Name);

        //        if (userInfo != null)
        //            Session["UserInfo"] = userInfo;
        //        else
        //            return RedirectToAction("LogOn", "Account");
        //    }

        //    List<Project> projects = ProjectRepository.GetProjectsToReview(int.Parse(userInfo.UserID));
        //    return View(projects);
        //}

        //[HttpPost]
        //public ActionResult AddProjectReviewFeedback(int projectID, string reviewFeedback)
        //{
        //    ProjectRepository.UpdateProject(projectID, reviewFeedback);
        //    return Json("Project Review Feedback updated successfully");
        //}

        //[Authorize]
        //[HttpGet]
        //public ActionResult EditProject(int projectID)
        //{
        //    Project project = ProjectRepository.GetProject(projectID);
        //    return View(project);
        //}


        private UserInfo GetUserInfo()
        {
            UserInfo userInfo = Session["UserInfo"] as UserInfo;
            if (Request.IsAuthenticated && userInfo == null)
            {
                //Store the User Info in a Session
                userInfo = UserRepository.GetUserInfo(User.Identity.Name);

                if (userInfo != null)
                    Session["UserInfo"] = userInfo;
            }
            return userInfo;
        }


        [Authorize]
        [HttpGet]
        public ActionResult Index()
        {
            UserInfo userInfo = GetUserInfo();

            if (userInfo == null)
                return RedirectToAction("LogOn", "Account");

            //if (userInfo.UserID.Equals("abetteam", StringComparison.OrdinalIgnoreCase))
            //    return RedirectToAction("Reports", "Home");

            ViewBag.ProjectID = 0;
            //ViewBag.ProjectExaminationDate = ProjectRepository.GetProjectExaminationDate();

            List<ProjectSummary> yourProjects = null;


            ViewBag.UserName = userInfo.LoginName;

            if (userInfo.IsFaculty)
            {
                int? periodID = null;
                if (TempData["PeriodID"] != null)
                    periodID = int.Parse(TempData["PeriodID"].ToString());
                else
                    periodID = ProjectRepository.GetDefaultProjectPeriodID();

                ViewData["PeriodID"] = periodID;

                yourProjects = ProjectRepository.GetSupervisedProjects(int.Parse(userInfo.UserID), periodID.Value);

                //If no projects then try next year or project proposals
                if (yourProjects == null || yourProjects.Count == 0)
                {
                    IList<int> periodIds = new List<int>();
                    int nextYearPeriodID = ProjectRepository.GetNextYearProjectPeriodId();
                    if (nextYearPeriodID != periodID.Value)
                        periodIds.Add(nextYearPeriodID);
                    periodIds.Add(0);

                    foreach (var periodId in periodIds)
                    {
                        yourProjects = ProjectRepository.GetSupervisedProjects(int.Parse(userInfo.UserID), periodId);

                        if (yourProjects != null && yourProjects.Count > 0)
                        {
                            ViewData["PeriodID"] = periodId;
                            break;
                        }
                    }
                }

                if (yourProjects == null || yourProjects.Count == 0)
                {
                    ViewBag.Message = "You have no projects.";
                    ViewBag.CanAddProject = ProjectRepository.CanAddProject(int.Parse(userInfo.UserID));
                }
                else
                    ViewBag.CanAddProject = ProjectRepository.CanAddProject(int.Parse(userInfo.UserID));


            }
            else
            {
                ViewBag.StudentID = userInfo.UserID;
                int projectID = ProjectRepository.GetStudentProjectID(userInfo.UserID);
                ViewBag.ProjectID = projectID;
                if (projectID == 0)
                    ViewBag.Message = string.Format("Senior Project Pre-Registration for Fall {0}", DateTime.Now.Year);
                else
                    yourProjects = new List<ProjectSummary> { ProjectRepository.GetProjectSummary(projectID, 0) };

                if (yourProjects != null)
                {
                    yourProjects.ForEach(p => p.Role = "Student");
                }
            }

            ViewBag.Ratings = GradingRepository.GetRatings(true);

            return View(yourProjects);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Index(int? projectID, int? periodID)
        {
            if (periodID != null)
            {
                TempData["PeriodID"] = periodID;
                return RedirectToAction("Index", "Home");
            }
            else if (projectID == null)
                return RedirectToAction("Index", "Home");
            else
            {
                //TempData["projectID"] = projectID.Value;
                return RedirectToAction("Grading", "Home", new { projectID = projectID });
            }
        }

        [HttpPost]
        [Authorize]
        public JsonResult ReleaseGrades(int projectID, int ratingId, string comments)
        {
            try
            {
                GradingRepository.AddEvaluationOfAddressingFeedback(projectID, ratingId, comments);
                ProjectRepository.SetProjectAsComplete(projectID);
                //Project {0} was successfully marked as complete. 
                var message = string.Format("The students can now access their grades.", projectID);
                return Json(new
                {
                    success = true,
                    id = projectID,
                    message = message
                });
            }
            catch (Exception ex)
            {
                var message = string.Format("Opertion failed because : {0}.\n Please try again", ex.Message);
                return Json(new
                {
                    success = true,
                    id = projectID,
                    message = message
                });
            }
        }

       
        [HttpGet]
        [Authorize]
        public ActionResult Projects()
        {
            ViewBag.Message = "Projects";
            ViewData["PeriodID"] = ProjectRepository.GetDefaultProjectPeriodID();
            var projects = ProjectRepository.GetProjectsSummary("ProjectsByPeriod", int.Parse(ViewData["PeriodID"].ToString()));
            return View(projects);
        }

        [HttpGet]
        [Authorize]
        public ActionResult Reports()
        {
            return View();
        }

        [HttpGet]
        [Authorize]
        public ActionResult CEProjects()
        {
            ViewBag.Message = "Preregistered CE Senior Design Projects for academic year 2011-2012";
            ViewData["PeriodID"] = ProjectRepository.GetDefaultProjectPeriodID();
            var projects = ProjectRepository.GetProjectsSummary("ProjectsByPeriod", int.Parse(ViewData["PeriodID"].ToString()));
            var ceProjects = projects.Where(p => p.Major != null && p.Major.Contains("CE") && !string.IsNullOrEmpty(p.Students) && !string.IsNullOrEmpty(p.Supervisors)).ToList();
            return View(ceProjects);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Projects(int periodID)
        {
            ViewBag.Message = "Projects";
            ViewData["PeriodID"] = periodID;

            var projects = ProjectRepository.GetProjectsSummary("ProjectsByPeriod", periodID);
            return View(projects);
        }

        public ActionResult Ping()
        {
            return Content(".");
        }

        private void PopulateDropDowns()
        {
            var inCollaborationWithEnum = new List<SelectListItem>()
            {
                new SelectListItem { Text = "Industry", Value = "Industry" },
                new SelectListItem { Text = "Government", Value = "Government" },
                new SelectListItem { Text = "Community Organization", Value = "Community Organization" }
            };

            var inCollaborationWithList = new SelectList(inCollaborationWithEnum, "Value", "Text");
            ViewBag.InCollaborationWithList = inCollaborationWithList;
        }

        //private string ControlToString(string controlPath, object model)
        //{
        //    CshtmlView control = new CshtmlView(controlPath);

        //    HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter());
        //    control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);

        //    string value = ((StringWriter)writer.InnerWriter).ToString();

        //    return value;
        //}
    }
}
